require('../plugins/jq-validate/jquery.validate.js')
require('../plugins/layer/layer.js') //弹出层js
function AddFunCommon(formid, config) {

	this.$form = $(formid);
	this.url = config.url;
	this.type = config.type;
	this.postdata = config.postdata || {};
	this.validate = config.validate;
	this.formtype = config.formtype || 'page'
	this.init();
	
}
AddFunCommon.prototype.init = function() {
	let _self = this;
	this.$form.validate({
		rules: _self.validate.rules,
		messages: _self.validate.errmsg,
		submitHandler:function() {
			_self.submit()
		},
		// debug:true
	})
	// this.setDefault();
}
AddFunCommon.prototype.submit = function() {
	
	
	let _self = this;
	let data = this.$form.serializeArray();
	if(typeof _self.postdata == 'undefined') {
		_self.postdata = {}
	}
	$.each(data, function(i, field){
		_self.postdata[field.name] = field.value
      // $("#results").append(field.name + ":" + field.value + " ");
    });
    
	$.ajax({
		url: _self.url,
		type: _self.type,
		dataType:'json',
		data: _self.postdata,
		success: function(res) {
			if(res.status === 1) {
				layer.msg('添加成功', {
		  			time: 500
		  		})
		  		if(_self.formtype == 'modal') {
		  			let $modal = _self.$form.closest( 'div.modal' );
		  			$modal.modal('hide');
		  			_self.$form[0].reset();
		  			location.reload()
		  		}else {
		  			setTimeout(function() {
	                	location.reload()
	            	}, 1000)
		  		}
		  		
			}else {
				layer.msg('添加失败，请稍后重试', {
		  			time: 500
		  		});
		  		if(_self.formtype == 'modal') {
		  			let $modal = _self.$form.closest( 'div.modal' );
		  			$modal.modal('hide');
		  		}
			}
		},
		error: function(res) {
			layer.msg('添加失败，请稍后重试', {
	  			time: 500
	  		})
		}
	})
	

	
}
export {AddFunCommon}